import { USER_CFG_KEY, UserSetting, ROLE_ENUM } from '@/config'
import { MetaStorage } from '@/utils'
import { defineStore } from 'pinia'
import { computed, type ComputedRef, ref } from 'vue';
import { UserSetting as UserType } from "@/types/config"

export const useUserStore = defineStore('user', () => {

    let userConfig = ref<UserType>(MetaStorage.getLocal(USER_CFG_KEY) ?? UserSetting)

    let role: ComputedRef<ROLE_ENUM> = computed(() => userConfig.value.role)

    let userInfo: ComputedRef<Record<string, any>> = computed(() => userConfig.value.userInfo)

    let token: ComputedRef<string> = computed(() => userConfig.value.token)

    function setUserConfig(config: UserType) {
        userConfig.value = config
        upDateStorage(config)
    }

    function deleteUserConfig() {
        userConfig.value = UserSetting
        upDateStorage(userConfig.value)
    }

    function setRole(role: ROLE_ENUM) {
        userConfig.value.role = role
        upDateStorage(userConfig.value)
    }

    function setUserInfo(userInfo: Record<string, any>) {
        userConfig.value.userInfo = userInfo
        upDateStorage(userConfig.value)
    }

    function setToken(token: string) {
        userConfig.value.token = token
        upDateStorage(userConfig.value)
       
    }

    function upDateStorage(config: UserType){
        MetaStorage.setLocalDeep(USER_CFG_KEY, config as UserType)
    }


    return {
        userConfig,
        role,
        userInfo,
        token,
        setUserConfig,
        setRole,
        setUserInfo,
        setToken,
        deleteUserConfig
    }
})